const express = require('express');
const router = express.Router();
const CompanyHistory = require('../models/companyHistory');
const simpleAmountToChinese = require('../utils')
const Docxtemplater = require('docxtemplater');
const PizZip = require('pizzip');
const fs = require('fs-extra');
const path = require('path');

// 新增接口 - 支持单条和批量新增
router.post('/company-history', async (req, res) => {
    try {
        const { data } = req.body;
        
        if (!data) {
            return res.status(400).json({
                success: false,
                message: '缺少数据参数',
                code:40001
            });
        }

        // 判断是单条还是批量
        if (Array.isArray(data)) {
            // 批量新增
            const records = await CompanyHistory.bulkCreate(data, {
                validate: true,
                individualHooks: true
            });
            
            res.json({
                success: true,
                message: `成功新增 ${records.length} 条记录`,
                data: records,
                code:10000
            });
        } else {
            // 单条新增
            const record = await CompanyHistory.create(data);
            
            res.json({
                success: true,
                message: '新增成功',
                data: record,
                code:10000
            });
        }
    } catch (error) {
        console.error('新增记录错误:', error);
        res.status(500).json({
            success: false,
            message: '新增记录失败',
            error: error.message,
            code:40002
        });
    }
});

// 删除接口 - 支持单个和多个删除
router.delete('/company-history', async (req, res) => {
  try {
    const { ids } = req.body;
    
    if (!ids) {
      return res.status(400).json({
        success: false,
        message: '缺少ID参数',
        code:40003
      });
    }

    // 将单个ID转换为数组格式
    const idArray = Array.isArray(ids) ? ids : [ids];
    
    // 删除记录
    const deletedCount = await CompanyHistory.destroy({
      where: {
        id: idArray
      }
    });
    res.json({
        success: true,
        message: `成功删除 ${deletedCount} 条记录`,
        data: { deletedCount },
        code:10000
    });
    } catch (error) {
        console.error('删除记录错误:', error);
        res.status(500).json({
            success: false,
            message: '删除记录失败',
            error: error.message,
            code:40004
        });
    }
});

// 可选：获取所有记录的接口
router.get('/company-history', async (req, res) => {
    try {
        const records = await CompanyHistory.findAll({
            order: [['created_at', 'DESC']]
        });
        
        res.json({
            success: true,
            data: records,
            code:10000
        });
    } catch (error) {
        console.error('获取记录错误:', error);
        res.status(500).json({
            success: false,
            message: '获取记录失败',
            error: error.message,
            code:40005
        });
    }
});

// 生成Word文档接口
router.get('/generate-doc', async (req, res) => {
try {
    const { year, month, day } = req.query;

    if (!year || !month || !day) {
        return res.status(400).json({
            success: false,
            message: '缺少year、month或day参数'
        });
    }

    // 查询数据库中的数据
    const records = await CompanyHistory.findAll({
        where: {
            year: parseInt(year),
            month: parseInt(month),
            day: parseInt(day)
        },
        order: [['created_at', 'ASC']]
    });

    if (records.length === 0) {
        return res.status(404).json({
            success: false,
            message: '未找到指定日期的数据'
        });
    }

    // 处理数据格式
    const data = records.map(item => ({
        year: item.year,
        month: item.month,
        day: item.day,
        name: item.name,
        account: item.account,
        bank_name: item.bank_name,
        amount: parseFloat(item.amount).toFixed(2),
        upAccount: simpleAmountToChinese(parseFloat(item.amount)),
        remark: item.remark || ''
    }));

    // 读取Word模板文件
    const templatePath = path.join(__dirname, '../doc/pay-modules.docx');
    
    if (!await fs.pathExists(templatePath)) {
        return res.status(404).json({
            success: false,
            message: '模板文件不存在'
        });
    }

    const content = await fs.readFile(templatePath, 'binary');
    const zip = new PizZip(content);
    const doc = new Docxtemplater(zip, {
        paragraphLoop: true,
        linebreaks: true
    });

    // 设置模板数据
    doc.setData({
        C: data
    });

    try {
        // 渲染模板
        doc.render();
    } catch (error) {
        console.error('模板渲染错误:', error);
        return res.status(500).json({
            success: false,
            message: '模板渲染失败',
            error: error.message
        });
    }

    // 生成输出文件
    const buffer = doc.getZip().generate({
        type: 'nodebuffer',
        compression: 'DEFLATE'
    });

    // 设置响应头
    const fileName = `付款凭证_${year}年${month}月${day}日.docx`;
    res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document');
    res.setHeader('Content-Disposition', `attachment; filename="${encodeURIComponent(fileName)}"`);
    res.setHeader('Content-Length', buffer.length);

    // 发送文件
    res.send(buffer);

} catch (error) {
    console.error('生成文档错误:', error);
    res.status(500).json({
        success: false,
        message: '生成文档失败',
        error: error.message
    });
}
});

module.exports = router;